const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            dataForm:{
                Summarize:'',
            },
            base_cycle: [],
            innovation_mechanism: [],
            organization: [],
            innovation_mechanism_details_agencies: [],
            isfirst: true
        };
    },
    mounted() {
        this.getCategory();
    },
    watch: {
        childDataForm(val) {
            if (this.action == 'Modify' && this.isfirst) {
                let str = val.map(i => "'" + i.Innovation_Mechanism_Detail_SerialNumber + "'").join(',')
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    type: "POST",
                    data: {
                        Data: 'innovation_mechanism_details_agencies',
                        Condition: "Row_Status='0' AND Innovation_Mechanism_Detail_SerialNumber IN (" + str + ")",
                    },
                    success: (data) => {
                        this.innovation_mechanism_details_agencies = data; // 直接使用 this
                        let options = this.organization;
                        val.forEach(item => {
                            let arr = data.filter(i => i.Innovation_Mechanism_Detail_SerialNumber == item.Innovation_Mechanism_Detail_SerialNumber).map(i => i.Government_Agencies_SerialNumber);
                            item.agencies = [];
                            arr.forEach(ite => {
                                item.agencies.push(this.configValue(options, ite));
                            })
                        })
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            }
        },
        organization(options) {
            if (this.action == 'Modify' && this.isfirst) {
                let str = this.childDataForm.map(i => "'" + i.Innovation_Mechanism_Detail_SerialNumber + "'").join(',');
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    type: "POST",
                    data: {
                        Data: 'innovation_mechanism_details_agencies',
                        Condition: "Row_Status='0' AND Innovation_Mechanism_Detail_SerialNumber IN (" + str + ")",
                    },
                    success: (data) => {
                        this.innovation_mechanism_details_agencies = data; // 直接使用 this
                        this.childDataForm.forEach(item => {
                            let arr = data.filter(i => i.Innovation_Mechanism_Detail_SerialNumber == item.Innovation_Mechanism_Detail_SerialNumber).map(i => i.Government_Agencies_SerialNumber);
                            item.agencies = [];
                            arr.forEach(ite => {
                                item.agencies.push(this.configValue(options, ite));
                            })
                        })
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            }
        }
    },
    methods: {
        configValue(options, val) {
            for (let i = 0; i < options.length; i++) {
                const item = options[i];
                if (item.Government_Agencies_SerialNumber == val) {
                    return [item.Government_Agencies_SerialNumber];
                } else if (item.children && item.children.length > 0) {
                    let arr = this.configValue(item.children, val);
                    if (arr) {
                        return [item.Government_Agencies_SerialNumber, ...arr];
                    }
                }
            }
        },
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'base_cycle',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.base_cycle = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'government_agencies',
                    NodeCode: "",
                },
                success: (data) => {
                    this.organization = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;

                let newInnovation_mechanism_details_agencies = [];
                if (action == 'Add') {
                    this.childDataForm.forEach((item, index) => {
                        item.Children = { innovation_mechanism_details_agencies: [] }
                        item.agencies.forEach(arr => {
                            item.Children.innovation_mechanism_details_agencies.push({
                                Government_Agencies_SerialNumber: arr[arr.length - 1]
                            })
                        })
                    })
                } else if (action == 'Modify') {
                    this.childDataForm.forEach((obj) => {
                        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                            //添加
                            obj.Children = { innovation_mechanism_details_agencies: [] }
                            obj.agencies.forEach(arr => {
                                obj.Children.innovation_mechanism_details_agencies.push({
                                    Government_Agencies_SerialNumber: arr[arr.length - 1]
                                })
                            })
                        } else {
                            //修改
                            obj.agencies.forEach((item) => {
                                let row = this.innovation_mechanism_details_agencies.filter(i => i.Innovation_Mechanism_Detail_SerialNumber == obj.Innovation_Mechanism_Detail_SerialNumber && i.Government_Agencies_SerialNumber == item[item.length - 1])[0];
                                if (row) {
                                    row.Row_Status = '0';
                                } else {
                                    newInnovation_mechanism_details_agencies.push({
                                        Innovation_Mechanism_Detail_SerialNumber:obj.Innovation_Mechanism_Detail_SerialNumber,
                                        Government_Agencies_SerialNumber:item[item.length - 1]
                                    })
                                }
                            })
                            this.innovation_mechanism_details_agencies.filter(item=>item.Innovation_Mechanism_Detail_SerialNumber == obj.Innovation_Mechanism_Detail_SerialNumber).forEach(item => {
                                if (!obj.agencies.some(i => i[i.length -1 ] == item.Government_Agencies_SerialNumber)) {
                                    item.Row_Status = '1';
                                } 
                            })
                        }
                    });
                }

                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_Table['innovation_mechanism_details_agencies'] =  this.innovation_mechanism_details_agencies;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    lJSONObject_DataSet['Add']['innovation_mechanism_details_agencies'] = newInnovation_mechanism_details_agencies;
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        lJSONObject_DataSet['Add'][ls_MainTableName] = lJSONArray_Record_Add;
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.location.href = './index.html'
                    }
                    this.loading = false;
                })
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-text-editor', ylTextEditor);
app.component('yl-cascader', ylCascader)
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
